﻿var FMAPortal = {
    variable:{
        
    },
    functions: {
        changeTypeObject : function(obj,newType){
            obj.removeClass("info");
            obj.removeClass("warning");
            obj.removeClass("error");
            obj.addClass(newType);
        },
        convertMessageToHtml:function(msg){
            var msgArray = msg.split("\n");
            var htmlList = document.createElement("ul");
            for(i in msgArray){
                if (msgArray[i].trim() != "") {
                    var htmlLi = document.createElement("li");
                    htmlLi.innerHTML = msgArray[i];
                    htmlList.appendChild(htmlLi);
                }
            }
            return htmlList.outerHTML;
        },
        required: function (obj) {
            switch (obj.prop("tagName").toLowerCase()) {
                case "input": {
                    obj.addClass("required");
                    break;
                }
                default: { break; }
            };
            return document.getElementById(obj.attr("aria-labelledby")).innerHTML + " belirtilmelidir.";
        },
        removeRequired: function (obj) {
            switch (obj.prop("tagName").toLowerCase()) {
                case "input": {
                    obj.removeClass("required");
                    break;
                }
                default: { break; }
            };
        },
        serializeForm : function(form){
            if (!form || form.nodeName !== "FORM") {
                return;
            }
            var result = {};
            var i, j, q = [];
            for (i = form.elements.length - 1; i >= 0; i = i - 1) {
                if (form.elements[i].name === "") {
                    continue;
                }
                switch (form.elements[i].nodeName) {
                    case 'INPUT':
                        switch (form.elements[i].type) {
                            case 'text':
                            case 'hidden':
                            case 'password':
                            case 'button':
                            case 'reset':
                            case 'submit':
                                result[form.elements[i].name] = encodeURIComponent(form.elements[i].value);
                                break;
                            case 'checkbox':
                                var value = [];
                                var elements = form.elements[form.elements[i].name]
                                for (j = elements.length - 1; j >= 0; j = j - 1) {
                                    if (elements[i].checked) {
                                        value.push(encodeURIComponent(form.elements[i].options[j].value));
                                    }
                                }
                                result[form.elements[i].name] = JSON.stringify(value);
                                break;
                            case 'radio':
                                if (form.elements[i].checked) {
                                    result[form.elements[i].name] = encodeURIComponent(form.elements[i].value);
                                }                                               
                                break;
                        }
                        break;
                    case 'file':
                        break; 
                    case 'TEXTAREA':
                        result[form.elements[i].name] = encodeURIComponent(form.elements[i].value);
                        break;
                    case 'SELECT':
                        switch (form.elements[i].type) {
                            case 'select-one':
                                result[form.elements[i].name] = encodeURIComponent(form.elements[i].value);
                                break;
                            case 'select-multiple':
                                var value = [];
                                for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
                                    if (form.elements[i].options[j].selected) {
                                        value.push(encodeURIComponent(form.elements[i].options[j].value));
                                    }
                                }
                                result[form.elements[i].name] = JSON.stringify(value);
                                break;
                        }
                        break;
                    case 'BUTTON':
                        switch (form.elements[i].type) {
                            case 'reset':
                            case 'submit':
                            case 'button':
                                result[form.elements[i].name] = encodeURIComponent(form.elements[i].value);
                                break;
                        }
                        break;
                }
            }
            console.log(result);
            return result;
        }
    },
    submit:function(form,success){
        var inputs = jQuery(form).find("input");
        var submitData = {};
        var messageContainer = jQuery(form).find(".form-submit-message");
        if (messageContainer.length > 0) {
            messageContainer.empty();
        }
        var checkForm = true;
        inputs.each(function () {
            var input = jQuery(this);
            if (input.prop("required") && input.val() == "") {
                var msg = FMAPortal.functions.required(input);
                if (messageContainer.length > 0) {
                    messageContainer.append(jQuery("<span class='error'/>").append(msg));
                }
                checkForm = false;
            } else {
                submitData = FMAPortal.functions.serializeForm(form);
                FMAPortal.functions.removeRequired(input);
            }
        });
        if (checkForm) {
            var url = form.action;
            var type = form.method;
            if (success == null || success == undefined)
                success = function (data) {
                    if (data != null || data != undefined) {
                        if (messageContainer.length > 0) {
                            messageContainer[0].innerHTML = data;
                        } else {
                            alert(data);
                        }
                    }
                }
            FMAPortal.ajax({
                url: url, type: type, data:submitData, success: success, error: function (err) {
                    if (messageContainer.length > 0) {
                        messageContainer[0].innerHTML = "İşlem başarısız oldu. <br/> " + err.status + " : " + err.statusText;
                        FMAPortal.functions.changeTypeObject(messageContainer,"error");
                    } else {
                        alert("İşlem başarısız oldu. \n\r " + err.status + " : " + err.statusText);
                    }
                }
            });
        }
    },
    ajax: function (settings) {
        var defaultSettings = {
            done: function (p) {

            }
        };
        settings = jQuery.extend({}, defaultSettings, settings);
        var doneTmp = settings.done;
        settings.done = function (d) {
            doneTmp(d);
            FMAPortal.loader.hide();
        };
        FMAPortal.loader.show();
        jQuery.ajax(settings);

    },
    loader: {
        show: function () {

        },
        hide: function () {

        }
    },
    alert: function (msg, title, type) {
        var alertContainer = jQuery("#alertContainer");
        if (title == null || title == undefined) {
            title = "";
        }
        if (type == null || type == undefined) {
            type = "info";
        }
        alertContainer.append(jQuery('<div class="alert alert-' + type + '"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>' + title + '</strong>' + msg + '</div>'));
    },
    initialize: function () {

        
    }

}

var FMAPortalAdmin = {
    variable: {
        pageFolderClass: "page-folder",
        fileItemIcon: "file-item-icon",
        fileItemUndefined: "file-item undefined",
        fileItemClass: "file-item",
        fileItemNameClass: "name",
        pageBody: function () { return jQuery(".page-body"); },
        pageMenu: function () { return jQuery(".page-menu"); },
        leftBarMenuButton: function () { return jQuery(".left-bar-menu-button"); },
    },
    container: {
        explorerPath: function () {
            return jQuery(".file-explorer");
        }
    },
    functions: {
        createFileItemIcons: function (fileItem) {
            var fileItemRoot = jQuery("<tr/>");
            if (fileItem.IsDirectory == true) {
                fileItemRoot.addClass(FMAPortalAdmin.variable.pageFolderClass);
            } else {
                if (fileItem.PageInfo !=null)
                    fileItemRoot.addClass(FMAPortalAdmin.variable.fileItemClass);
                else
                    fileItemRoot.addClass(FMAPortalAdmin.variable.fileItemUndefined);
            }
            var fileItemIcon = jQuery("<i/>");
            fileItemIcon.addClass(FMAPortalAdmin.variable.fileItemIcon);
            var fileItemName = jQuery("<span/>");
            var nameArray = fileItem.Name.split('\\');
            fileItemName.addClass(FMAPortalAdmin.variable.fileItemNameClass).text(nameArray[nameArray.length-1]);

            //fileItemRoot.append("<input type='hidden' value='" + JSON.stringify(fileItem) + "'>");
            var selectRowInput = jQuery("<input type='checkbox'/>");
            fileItemRoot.append(jQuery("<td class='tool'/>").append(selectRowInput));
            fileItemRoot.append(jQuery("<td class='tool'/>").append(jQuery("<i/>")));
            fileItemRoot.append(jQuery("<td class='tool'/>").append(jQuery("<i/>")));
            fileItemRoot.append(jQuery("<td class='tool'/>").append(jQuery("<i/>")));
            var fileItemObject = jQuery("<td class='name-container'/>").append(fileItemIcon).append(fileItemName);
            fileItemRoot.append(fileItemObject);
            fileItemObject.dblclick(function () {
                alert(fileItem.Name);
            });
            fileItemObject.click(function () {
                if(selectRowInput.prop("checked"))
                    selectRowInput.prop("checked", false);
                else
                    selectRowInput.prop("checked",true);


            });
            return fileItemRoot;
        },
        pageSave: function (form) {
            FMAPortal.submit(form, function (data) {
                var messageContainer = jQuery(form).find(".form-submit-message");
                if (data.isError == true) {
                    if (messageContainer.length > 0) {
                        messageContainer.empty();
                        FMAPortal.functions.changeTypeObject(messageContainer, "error");
                        messageContainer.html(FMAPortal.functions.convertMessageToHtml(data.data));
                    } else
                        alert(data.data);
                } else {
                    jQuery("#addPagesModal").modal('hide');
                    FMAPortal.alert(data.data, "", "info");
                    FMAPortalAdmin.services.getAllFileItem(document.getElementById('pagePath').value);
                }
            });
        }
    },
    services: {
        getAllFileItem: function (path) {
            FMAPortal.ajax({
                url: "/services/getAllFileItem",
                type: "POST",
                data: { p: path },
                success: function (result) {
                    if (result && result.isError==false) {
                        var data = result.data;
                        FMAPortalAdmin.container.explorerPath().empty();
                        for (itemKey in data) {
                            FMAPortalAdmin.container.explorerPath().append(FMAPortalAdmin.functions.createFileItemIcons(data[itemKey]));
                        }
                        document.getElementById("pagePath").value = path;
                    } else {
                        FMAPortal.alert(result.data, "Hata : ", "error");
                    }
                }
            });
        }
    },
    initialize: function () {
        FMAPortalAdmin.variable.leftBarMenuButton().click(function () {
            var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
            if (FMAPortalAdmin.variable.pageBody().hasClass("menu-close") || (width < 768 && !FMAPortal.variable.pageBody().hasClass("menu-open"))) {
                FMAPortalAdmin.variable.pageBody().addClass("menu-open")
                FMAPortalAdmin.variable.pageBody().removeClass("menu-close")
                FMAPortalAdmin.variable.pageMenu().addClass("menu-show");
                FMAPortalAdmin.variable.pageMenu().removeClass("menu-hide");
            } else {
                FMAPortalAdmin.variable.pageBody().addClass("menu-close")
                FMAPortalAdmin.variable.pageBody().removeClass("menu-open")
                FMAPortalAdmin.variable.pageMenu().addClass("menu-hide");
                FMAPortalAdmin.variable.pageMenu().removeClass("menu-show");
            }
        });
    }
}